package com.minelx.statementsplus.cha.webauto;

import com.minelx.landisk.filesystem.core.File;
import com.minelx.statementsplus.cha.core.IChaTask;
import com.minelx.statementsplus.cha.core.TaskCommitment;
import com.minelx.statementsplus.cha.webauto.ChaPage;
import com.minelx.statementsplus.cha.webauto.ChaPageFactory;
import com.minelx.statementsplus.cha.webauto.ResultFile;

import java.io.IOException;

import static com.minelx.landisk.filesystem.core.PathFactory.file;

public class SingleTask implements IChaTask {

	private final ChaPageFactory chaPageFactory;

	private final TaskCommitment commitment;

	private final File downloadedFile;

	public SingleTask(ChaPageFactory chaPageFactory, TaskCommitment commitment, File downloadedFile) {
		this.chaPageFactory = chaPageFactory;
		this.commitment = commitment;
		this.downloadedFile = downloadedFile;
	}

	@Override
	public void execute() {
		try (ChaPage chaPage = chaPageFactory.createChaPage()) {
			// do execute
			if (canExecute(chaPage)) {
				// do download
				File zipTemp = doDownload(chaPage);
				// do extraction
				doExtraction(zipTemp);
			}
		}
	}

	private boolean canExecute(ChaPage chaPage) {
		chaPage.explain(commitment);
		String tips = chaPage.executeForTips();
		return !tips.equals(ChaPage.TIPS___EMPTY_RECORD_AFTER_EXECUTION);
	}

	private File doDownload(ChaPage chaPage) {
		File zipTemp = downloadedFile.sibling("tmp_" + downloadedFile.getName() + ".zip").as(file());
		chaPage.getDownloadRequest().doDownload(zipTemp);
		return zipTemp;
	}

	private void doExtraction(File zipTemp) {
		try {
			File extractedCsv = new ResultFile(zipTemp).extractCsv();
			zipTemp.delete();
			extractedCsv.rename(downloadedFile.getName());
		} catch (IOException e) {
			throw new RuntimeException("something is wrong here", e);
		}
	}

	@Override
	public long progress() {
		return 666;
	}
}
